package com.roshan.domain;

import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.stereotype.Component;

@Configurable
@Component
public class CommunityDataOnDemand {

    private Random rnd = new SecureRandom();

    private List<Community> data;

    public Community getNewTransientCommunity(int index) {
        Community obj = new Community();
        setCode(obj, index);
        return obj;
    }

    public void setCode(Community obj, int index) {
        String code = "code_" + index;
        if (code.length() > 30) {
            code = code.substring(0, 30);
        }
        obj.setCode(code);
    }

    public Community getSpecificCommunity(int index) {
        init();
        if (index < 0)
            index = 0;
        if (index > (data.size() - 1))
            index = data.size() - 1;
        Community obj = data.get(index);
        return Community.findCommunity(obj.getId());
    }

    public Community getRandomCommunity() {
        init();
        Community obj = data.get(rnd.nextInt(data.size()));
        return Community.findCommunity(obj.getId());
    }

    public boolean modifyCommunity(Community obj) {
        return false;
    }

    public void init() {
        data = Community.findCommunityEntries(0, 10);
        if (data == null)
            throw new IllegalStateException("Find entries implementation for 'Community' illegally returned null");
        if (!data.isEmpty()) {
            return;
        }

        data = new ArrayList<com.roshan.domain.Community>();
        for (int i = 0; i < 10; i++) {
            Community obj = getNewTransientCommunity(i);
            try {
                obj.persist();
            } catch (ConstraintViolationException e) {
                StringBuilder msg = new StringBuilder();
                for (Iterator<ConstraintViolation<?>> it = e.getConstraintViolations().iterator(); it.hasNext();) {
                    ConstraintViolation<?> cv = it.next();
                    msg.append("[").append(cv.getConstraintDescriptor()).append(":").append(cv.getMessage())
                            .append("=").append(cv.getInvalidValue()).append("]");
                }
                throw new RuntimeException(msg.toString(), e);
            }
            obj.flush();
            data.add(obj);
        }
    }
}
